import store from '@/store/index.js'
const baseUrl = 'https://service.jiaoguanyi.com.cn/'  //正式站

// const baseUrl = 'http://jgyas/index.php/'  //本地

const request = (method, url, data, header = {}) => {
	return new Promise((resolve, reject) => {
		uni.request({
			method: method,
			url: baseUrl + url,
			data: data,
			dataType: 'json',
			header: {
				'token': store.state.token,
				'cache-control': 'no-cache'
				//'token': uni.getStorageSync("token")
			},
			success: (res) => {
				//300 跳转为登录页
				if (res.data.code === 300) {
					uni.showModal({
						title: '提示',
						content: res.data.msg,
						showCancel: false,
						success: function(res) {
							uni.reLaunch({
								url: "/pages/login/index",
								success: function(res) {
									uni.clearStorageSync();
								}
							});
						}
					})
				}
				if (res.data.code === 200) {
					resolve(res.data)
				} else {
					reject(res.data)
				}
				uni.stopPullDownRefresh();
				uni.hideLoading();
			},
			fail: (err) => {
				console.log('失败请求',err)
				uni.hideLoading();
				uni.stopPullDownRefresh();
				reject(err)
			}
		})
	})
}

export default function(method = 'get', url = '', data = {}) {
	method = method.toLowerCase();
	if (method == 'post') {
		return request('post', url, data)
	} else if (method == 'get') {
		//加上时间戳 老走缓存
		return request('get', url, {...data, time: Date.parse(new Date())})
	} else if (method == 'delete') {
		return request('delete', url, {
			params: data
		})
	} else if (method == 'put') {
		return request('put', url, data)
	} else {
		console.error('未知的method' + method)
		return false
	}
}
